<?php

namespace app\api\model;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\model\relation\HasOne;

/**
 * 用户领取的优惠券
 */
class CouponUser extends BaseModel
{
    protected $table = 'fa_store_coupon_user';

    /**
     * @param $userId
     * @param $couponId
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getUserCoupon($userId, $couponId)
    {
        return self::where('user_id',$userId)->where('coupon_id',$couponId)->find();
    }

    /**
     * 获取用户所有的优惠券
     * @param $userid
     * @return bool|\PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getUsableCoupons($userid,$with=[])
    {
        return self::where('user_id',$userid)->with($with)->where('status',0)->select();
    }

    /**
     * 关联优惠券
     * @return HasOne
     */
    public function coupon(): HasOne
    {
        return $this->hasOne(Coupon::class,'id','coupon_id');
    }
}